# -*- coding: utf-8 -*-

import frappe
import json
import copy
from frappe.model import no_value_fields
from easy_print.template_util import build_parameter,get_new_template,get_new_parameter_template


@frappe.whitelist()
def do_print(doc_type, doc_name): 
    data = {}
    data["parameters"] = []
    count = 1001
    doc = frappe.get_doc(doc_type, doc_name)    
    for item in doc.meta.fields:        
        if item.fieldtype not in no_value_fields:
            new_item = None            
            new_item = build_parameter(count, item.fieldname, item.fieldtype,getattr(doc, item.fieldname))
            data["parameters"].append(new_item)
            count += 1
        if item.fieldtype == "Table":
            lines = getattr(doc, item.fieldname)
            lines_json = frappe.as_json(lines)
            # print(lines_json)
            new_item = {
                "id": count,
                "name": item.fieldname,
                "type": "array",
                "eval": False,
                "pattern": "",
                "expression": "",
                "showOnlyNameType": False,
                "testData": lines_json,
                "children": [],
            }
            count += 1
            child_meta = frappe.get_meta(item.options)
            for sub_item in child_meta.fields:
                if sub_item.fieldtype not in no_value_fields:
                    new_sub_item = None                    
                    new_sub_item = build_parameter(count, sub_item.fieldname, sub_item.fieldtype,"")              
                    new_item["children"].append(new_sub_item)
                    count += 1
            data["parameters"].append(new_item)
    data["data"] = doc    
    frappe.publish_realtime('user:printer',data)
    return 'ok'